import requests
import re
import sys
import os
import time
import random
from typing import Optional, Dict

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 导入代理管理器
from proxy_manager import get_proxy, remove_proxy

def google_translate(word, to_lan='zh-CN', use_proxy=True, max_retries=3, timeout=20):
    """
    使用谷歌翻译API翻译文本
    
    参数:
        word: 要翻译的文本
        to_lan: 目标语言
        use_proxy: 是否使用代理
        max_retries: 最大重试次数
        timeout: 请求超时时间(秒)
    
    返回:
        翻译后的文本，如果失败则返回None
    """
    headers = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
        "downlink": "1.5",
        "origin": "https://www.google.com",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://www.google.com/",
        "rtt": "400",
        "sec-ch-prefers-color-scheme": "light",
        "sec-ch-ua": "\"Google Chrome\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
        "sec-ch-ua-arch": "\"x86\"",
        "sec-ch-ua-bitness": "\"64\"",
        "sec-ch-ua-form-factors": "\"Desktop\"",
        "sec-ch-ua-full-version": "\"135.0.7049.84\"",
        "sec-ch-ua-full-version-list": "\"Google Chrome\";v=\"135.0.7049.84\", \"Not-A.Brand\";v=\"8.0.0.0\", \"Chromium\";v=\"135.0.7049.84\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-model": "\"\"",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-ch-ua-platform-version": "\"10.0.0\"",
        "sec-ch-ua-wow64": "?0",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
        "x-client-data": "CI62yQEIo7bJAQipncoBCMGVywEIlqHLAQiSo8sBCIWgzQEI/qXOAQjd1s4BCO7mzgEIp+fOAQi7584BCOHpzgE=",
        "x-dos-behavior": "Embed"
    }
    cookies = {
        "HSID": "Ap3az3-RePB-YHuMk",
        "SSID": "Add0xOLH87fhfd_vr",
        "APISID": "ww0h31BkFpSDNSd1/AK9BBeHLV-9X81ddA",
        "SAPISID": "KfzSOjn8baVlXKqD/AKPmJjm3D0Z422MKf",
        "__Secure-1PAPISID": "KfzSOjn8baVlXKqD/AKPmJjm3D0Z422MKf",
        "__Secure-3PAPISID": "KfzSOjn8baVlXKqD/AKPmJjm3D0Z422MKf",
        "SID": "g.a000vgiALL8HoxEMFWt9m4QTRQ9Ll-_G6fDYY5t7JUZ7SzKKuOPZuqaieG8vgqvzV6SOWKbuLwACgYKAekSARYSFQHGX2Mi8HTOg8pPQCoqpxgc_HzrwRoVAUF8yKrZw95BiI7pjMcYig7gZdHm0076",
        "__Secure-1PSID": "g.a000vgiALL8HoxEMFWt9m4QTRQ9Ll-_G6fDYY5t7JUZ7SzKKuOPZO8wNS8DLMPPiLx52GvwmHwACgYKAa8SARYSFQHGX2Mi0EDMv-m_81biEihIyEaJbBoVAUF8yKqKI39roPYQMsyE322e09Ws0076",
        "__Secure-3PSID": "g.a000vgiALL8HoxEMFWt9m4QTRQ9Ll-_G6fDYY5t7JUZ7SzKKuOPZVHkBcfTBa9pWdF00SF8EuwACgYKAbQSARYSFQHGX2Mi6PktRH6FlYj3HLHsLjIwVBoVAUF8yKpKjtW89EI-q--BKstRvEB40076",
        "SEARCH_SAMESITE": "CgQI3J0B",
        "AEC": "AVcja2fx3tC2ERw3xHcaFQILbOUkDmgKa1qw8BoPH-kP6L-FKNZppjy74A",
        "__Secure-1PSIDTS": "sidts-CjIB7pHptcpfLLbHeg388YKQgLuhvGmcceWvMVmMYfotOK320KaNw82yPXho6dmKFZavOhAA",
        "__Secure-3PSIDTS": "sidts-CjIB7pHptcpfLLbHeg388YKQgLuhvGmcceWvMVmMYfotOK320KaNw82yPXho6dmKFZavOhA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FNu4K7FOr3_M8-e6pmDcxEnAd38XUFA",
        "__Secure-3PSIDCC": "AKEyXzVtFvYcnNwLz8jD0HY-pV11OrDJa1tK1lD4GqyZsg6azv7cJuSCLdh24PffNA_3saIzUjIv"
    }
    url = "https://www.google.com/async/translate"
    params = {
        "vet": "12ahUKEwiUyvLthdSMAxXo1TQHHXM3IQkQqDh6BAgPEC4..i",
        "ei": "oSz7Z9T1A-ir0-kP8-6ESQ",
        "opi": "89978449",
        "yv": "3",
        "_fmt": "pc",
        "cs": "0"
    }
    data = {
        "async": f"translate,sl:auto,tl:{to_lan},st:{word},id:1744514241980,qc:true,ac:true,_id:tw-async-translate,_pms:s,_fmt:pc,_basejs:/xjs/_/js/k=xjs.s.en_GB.jxc-mPn7xME.2018.O/am=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAABAAAUBIAAAAAAAAAAgAAQAAAAAAACACQAAAAAAAAkIAAFBAgAAAEAAAAAAAACYAAAEBCsAAAUAAAAAAAAAAACAAAAAAICACID3_YMBAAAAAAAAAAAAAAAAACAAEgAAAAAAAADABQCAADgAgJBdgAAAAAAAAAAAIAAAAAAAAEAAAAAAAAACAAAAKAAAAAAAAAAAQAAAAAAAAAAgAAAAgAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAGgAAKACAAH4AAAAAAAAcAAAAgAAAAADgGKMACAAAAAAAAMgDwOMBHFJQAAAAAAAAAAAAAAAAEICCYA6kXxAgAAAAAAAAAAAAAAAAAACAFEET1xoAIA/dg=0/br=1/rs=ACT90oHG_7piHAz9bA0qBIkCPDZ1w3ydaQ,_basecss:/xjs/_/ss/k=xjs.s.yn-jfZ9VRvs.L.B1.O/am=AMQjEAIAAAABAAAgBIAKQAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAEAAAAAAAAAQAGAMEAEAAAAKAAAAgOAEAGQHAAAAAD4AhjhVABAAAAAAAAFAAgAAAAAAQACAAACQgQAAgCgAAAAAIEAQwgAAAQDYAACARAAACAIAAAQBAwDIAAAAAAABAHAqACAOAIAAADAAAHAABAAJAAAAgFBYAAQAAIAEAAAAAAAAIAAAAEAAAIAIAByCYQAEKgAM4AgAAAACiACAQAAAACAAQAgAiAEACgAAAQIADwAIwAcAWIgGiAAAUAADECAAKAQABABsAIAAAACABAAAQAgAigDgGKMACAAAAAAAAEACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAEA/br=1/rs=ACT90oFZGO5SeLLcmshTg5aQZrfs7qrKIg,_basecomb:/xjs/_/js/k=xjs.s.en_GB.jxc-mPn7xME.2018.O/ck=xjs.s.yn-jfZ9VRvs.L.B1.O/am=AMQjEAIAAAABAAAgBIAKQAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAEAAAAAAAAAQAGBMEAUBIAAKAAAAgOAkAGQHAAAAAD6AjzhVABAAAAkIAAFBAgAAAEAAQACAAACYgQAEhCsAAAUAIEAQwgAAAQDYAACARICACIL3_YcBAwDIAAAAAAABAHAqACAOEoAAADAAAHDABQCJADgAgNBdgAQAAIAEAAAAIAAAIAAAAEAAAIAIAByCYQAEKgAM4AgAAAACyACAQAAAACAgQAgAiAEACgEAAQIADwAIwAcAWIgGiAAAUAADGiAAKASABH5sAIAAAACcBAAAwAgAigDgGKMACAAAAAAAAMgDwOMBHFJQAAAAAAAAAAAAAAAAEICCYA6kXxAgAAAAAAAAAAAAAAAAAACAFEET1xoAIA/d=1/ed=1/dg=0/br=1/ujg=1/rs=ACT90oEACZ-FegylkdPIZ3yUQalTU06BVw"
    }
    
    # 用于跟踪已经尝试过的代理
    tried_proxies = set()
    current_retry = 0
    
    while current_retry < max_retries:
        # 随机延迟，避免请求过于频繁
        if current_retry > 0:
            delay = random.uniform(1.0, 3.0)
            time.sleep(delay)
        
        try:
            # 获取代理（如果需要的话）
            proxies = None
            if use_proxy:
                try:
                    proxies = get_proxy()
                    # 如果这个代理已经尝试过，并且还有其他尝试机会，则重新获取
                    proxy_str = str(proxies)
                    if proxy_str in tried_proxies and current_retry < max_retries - 1:
                        continue
                    tried_proxies.add(proxy_str)
                except Exception as e:
                    print(f"获取代理失败: {str(e)}，将尝试不使用代理请求")
            
            # 发送请求
            response = requests.post(
                url, 
                headers=headers, 
                cookies=cookies, 
                params=params, 
                data=data,
                proxies=proxies,
                timeout=timeout  # 使用可配置的超时时间
            )
            
            # 检查响应状态
            if response.status_code != 200:
                print(f"请求失败，状态码: {response.status_code}，重试中... (尝试 {current_retry+1}/{max_retries})")
                if use_proxy and proxies:
                    remove_proxy(proxies)  # 移除失败的代理
                current_retry += 1
                continue
            
            # 检查是否被谷歌阻止（通常会重定向到验证页面）
            if "Our systems have detected unusual traffic from your computer network" in response.text:
                print(f"请求被谷歌拦截，可能需要验证码，尝试使用其他代理... (尝试 {current_retry+1}/{max_retries})")
                if use_proxy and proxies:
                    remove_proxy(proxies)  # 移除被拦截的代理
                current_retry += 1
                continue
                
            # 使用正则表达式匹配 <span id="tw-answ-target-text"> 中的内容
            pattern = r'<span id="tw-answ-target-text">(.*?)</span>'
            matches = re.findall(pattern, response.text, re.DOTALL)
            
            # 如果匹配成功，返回结果
            if matches:
                result = matches[0].strip()
                if result:  # 确保得到的结果不是空字符串
                    return result
            
            # 尝试使用另一种模式匹配（作为备用）
            alt_pattern = r'id="tw-answ-target-text"[^>]*>(.*?)</span>'
            alt_matches = re.findall(alt_pattern, response.text, re.DOTALL)
            if alt_matches:
                result = alt_matches[0].strip()
                if result:
                    return result
                
            # 如果没有匹配结果但响应成功
            error_msg = f"未找到翻译结果，响应长度: {len(response.text)}，重试中... (尝试 {current_retry+1}/{max_retries})"
            print(error_msg)
            
            # 记录更详细的调试信息
            if len(response.text) < 200:
                print(f"响应内容: {response.text}")
            else:
                print(f"响应内容前200个字符: {response.text[:200]}...")
            
            current_retry += 1
            
        except requests.exceptions.RequestException as e:
            # 网络请求异常，如连接超时、连接错误等
            print(f"网络请求异常: {str(e)}，重试中... (尝试 {current_retry+1}/{max_retries})")
            if use_proxy and 'proxies' in locals() and proxies:
                remove_proxy(proxies)  # 移除失败的代理
            current_retry += 1
        except Exception as e:
            # 其他未预期的异常
            print(f"翻译过程中出现异常: {str(e)}，重试中... (尝试 {current_retry+1}/{max_retries})")
            import traceback
            traceback.print_exc()  # 打印完整的异常堆栈信息
            if use_proxy and 'proxies' in locals() and proxies:
                remove_proxy(proxies)  # 移除失败的代理
            current_retry += 1
    
    print(f"翻译失败，已达到最大重试次数: {max_retries}")
    return None

def translate_from_ch_to_en(word, use_proxy=True, max_retries=3, timeout=20):
    """
    将中文翻译为英文
    
    参数:
        word: 要翻译的中文文本
        use_proxy: 是否使用代理
        max_retries: 最大重试次数
        timeout: 请求超时时间(秒)
    
    返回:
        翻译后的英文文本，如果失败则返回None
    """
    if not word or not isinstance(word, str):
        return None
        
    word = word.replace(',', '，')
    return google_translate(word, to_lan='en', use_proxy=use_proxy, max_retries=max_retries, timeout=timeout)

def translate_from_en_to_cn(word, use_proxy=True, max_retries=3, timeout=20):
    """
    将英文翻译为中文
    
    参数:
        word: 要翻译的英文文本
        use_proxy: 是否使用代理
        max_retries: 最大重试次数
        timeout: 请求超时时间(秒)
    
    返回:
        翻译后的中文文本，如果失败则返回None
    """
    if not word or not isinstance(word, str):
        return None
        
    word = word.replace(',', ' ')
    return google_translate(word, use_proxy=use_proxy, max_retries=max_retries, timeout=timeout)

if __name__ == '__main__':
    # 初始化代理池
    from proxy_manager import init_proxy_pool
    init_proxy_pool(max_use_count=5, min_pool_size=10)
    
    # 测试翻译功能
    english_result = translate_from_ch_to_en("苹果手机和平板电脑市场会被小米和华为瓜分吗?", use_proxy=True)
    print(f"中译英结果: {english_result}")
    
    chinese_result = translate_from_en_to_cn("The stock price has continued to rise, the market sentiment is high, and the market performance is optimistic", use_proxy=True)
    print(f"英译中结果: {chinese_result}")
